import axios, { HttpStatusCode } from "axios";
import type { AxiosInstance, AxiosError, AxiosRequestConfig } from "axios";

const service: AxiosInstance = axios.create({
    baseURL: '/api',
    timeout: 3000
})


// @ts-ignore
service.interceptors.request.use((config: AxiosRequestConfig) => {
    const token = sessionStorage.getItem('token')
    // @ts-ignore
    if(token) {
        config.headers!.Authorization = JSON.parse(token).token
    }
    return config
}, (error: AxiosError) => {
    return Promise.reject(error)
})

// @ts-ignore
service.interceptors.response.use((response: Result | PageResult) => {
    if(response.statusCode === HttpStatusCode.Ok || HttpStatusCode.Created) {
        return Promise.resolve(response.data)
    } else {
        return Promise.reject(response.data)
    }
}, (error: AxiosError) => {
    return Promise.reject(error)
})

export default service
